package com.tanhua.manage.config;

import com.alibaba.fastjson.JSONObject;
import com.tanhua.manage.pojo.Admin;
import com.tanhua.manage.pojo.OperationLog;
import com.tanhua.manage.service.AdminService;
import com.tanhua.manage.service.OperationLogService;
import com.tanhua.manage.util.GetDataFromRequest;
import com.tanhua.manage.util.IpAdrressUtil;
import com.tanhua.manage.util.NoAuthorization;
import com.tanhua.manage.util.UserThreadLocal;
import com.tanhua.manage.vo.UserFreezeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private AdminService adminService;

    @Autowired
    private OperationLogService operationLogService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
        if (method.equals("OPTIONS")) {
            //跳过跨域中的OPTIONS请求
            return true;
        }

        //判断，请求的方法是否包含了 NoAuthorization ，如果包含了，就不需要做处理
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            NoAuthorization annotation = handlerMethod.getMethod().getAnnotation(NoAuthorization.class);
            if (annotation != null) {
                return true;
            }
        }
        if(true){  return true;}
        String token = request.getHeader("Authorization");
        token = token.replace("Bearer ", "");
        Admin admin = adminService.queryUserByToken(token);
        if (null == admin) {
            response.setStatus(401); //无权限
            return false;
        }
        admin.setToken(token);
        // 存储到当前的线程中
        UserThreadLocal.set(admin);
        return true;
    }

    private static HashMap<String, String[]> map= new HashMap();
    private static HashMap<Integer, String> freezingTimemap= new HashMap();
    private static HashMap<Integer, String> freezingrangemap= new HashMap();
    static {
        String[] pass = {"List<String>","ids","消息通过"};
        map.put("pass",pass);
        String[] reject = {"List<String>","ids","消息拒绝"};
        map.put("reject",reject);
        String[] revocation = {"List<String>","ids","消息撤销"};
        map.put("revocation",revocation);
        String[] freeze = {"UserFreezeVo","vo","冻结操作"};
        map.put("freeze",freeze);
        String[] unfreeze  = {"UserFreezeVo","vo","解冻操作"};
        map.put("unfreeze",unfreeze);

        freezingTimemap.put(1,"冻结3天");
        freezingTimemap.put(2,"冻结7天");
        freezingTimemap.put(3,"永久冻结");

        freezingrangemap.put(1,"冻结登录");
        freezingrangemap.put(2,"冻结发言");
        freezingrangemap.put(3,"冻结发布动态");
    }
    @Override
    ////public void afterCompletion(HttpServletRequest request,
    //                            HttpServletResponse response,
    //                            Object handler,
    //                            Exception ex) throws Exception {
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object handler,
                           ModelAndView modelAndView) throws Exception {
        OperationLog operationLog= new OperationLog();
        String requestURI = request.getRequestURI();
        System.out.println(requestURI);
        String[] split = requestURI.split("/");
        String s = split[split.length - 1];
        String[] strings = map.get(s);
        if (strings ==null){
            return;
        }
        JSONObject requestJsonObject = GetDataFromRequest.getRequestJsonObject(request);
        //strings[0];
        if ("UserFreezeVo".equals(strings[0])){
            UserFreezeVo userFreezeVo = JSONObject.parseObject(String.valueOf(requestJsonObject), UserFreezeVo.class);
            Long userId = userFreezeVo.getUserId();
            if("freeze".equals(s)) {
                String freezingTime = freezingTimemap.get(userFreezeVo.getFreezingTime());
                String freezingRange = freezingrangemap.get(userFreezeVo.getFreezingRange());
                String reasonsForFreezing = userFreezeVo.getReasonsForFreezing();
                StringBuilder desCribe = new StringBuilder("将[");
                desCribe.append(userId).append("]").append(freezingTime).append(",").append(freezingRange).append(",").append(reasonsForFreezing);
                operationLog.setDesCribe(desCribe.toString());
            }else {
                String reasonsForThawing = userFreezeVo.getReasonsForThawing();
                StringBuilder desCribe = new StringBuilder("将[");
                desCribe.append(userId).append("]").append(strings[2]).append("原因：").append(reasonsForThawing);
                operationLog.setDesCribe(desCribe.toString());
            }
        }else {
            //UserFreezeVo userFreezeVo = JSONObject.parseObject(String.valueOf(requestJsonObject), List<String.class>);
            operationLog.setDesCribe(operationLog.getOperation());
        }
        //String username = UserThreadLocal.get().getUsername();
        //因为测试原因未登入所有使用固定的用户信息
        String username = "张三";
        String roleName = "业务专员";
        //通过request获取到客户端的IP
        String ipAddr = IpAdrressUtil.getIpAddr(request);
        //设置日志对象
        operationLog.setIp(ipAddr);
        operationLog.setUsername(username);
        operationLog.setRoleName(roleName);
        operationLog.setLogTime(System.currentTimeMillis());
        operationLog.setOperation(strings[2]);
        //调用对象保持日志
        operationLogService.saveOperationLog(operationLog);
    }
}